#include "client.h"
typedef struct trans_train_s{
    int type;
    int length;
    char context[4096];
}trans_train_t;
int main(int argc, char *argv[]){   

    ARGS_CHECK(argc,3);
    int sockfd = socket(AF_INET,SOCK_STREAM,0);
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(atoi(argv[2]));
    addr.sin_addr.s_addr = inet_addr(argv[1]);
    int ret = connect(sockfd,(struct sockaddr*)&addr,sizeof(addr));
    ERROR_CHECK(ret,-1,"connect");


    int epfd = epoll_create(1);

    //监听网络连接
    struct epoll_event event1;
    event1.events = EPOLLIN;
    event1.data.fd = sockfd;
    epoll_ctl(epfd,EPOLL_CTL_ADD,sockfd,&event1);
    //监听键盘输入
    struct epoll_event event2;
    event2.events = EPOLLIN;
    event2.data.fd = STDIN_FILENO;
    epoll_ctl(epfd,EPOLL_CTL_ADD,STDIN_FILENO,&event2);

    char buf[1024];
    struct epoll_event readyset[1024];
    //salt目前是20个字符
    char salt[21]={0};

    while(1){
        int readynum = epoll_wait(epfd,readyset,1024,-1);
        for(int i=0;i<readynum;++i){
            //键盘输入就绪,记得处理输入为空的情况
            if(readyset[i].data.fd==STDIN_FILENO){
                bzero(buf,sizeof(buf));
                read(STDIN_FILENO,buf,sizeof(buf));
                commandManage(buf,sockfd,salt);
            }
            if(readyset[i].data.fd == sockfd){
                //是否跳过打印context的内容的标志位
                int skip_print = 0;

                trans_train_t train;
                bzero(&train,sizeof(train));
                int ret = recv(sockfd,&train.type,sizeof(int),0);
                if(ret == 0){
                    printf("server quit!\n");
                    return 0;
                }
                recv(sockfd,&train.length,sizeof(int),0);
                recv(sockfd,&train.context,train.length,0);
                // if(train.type==gets的值){
                // 调用接受文件的函数；
                // return 0;
                // }
                if(train.type==31){
                    //测试
                    // int ll = strlen(train.context);
                    // printf("ll=%d\n",ll);
                    // printf("%s\n",train.context);
                    int salt_length = strlen(train.context);
                    if(salt_length != 20){
                        //盐值接收错误，后续处理
                        printf("salt_length is wrong,salt_length = %d\n",salt_length);
                    }else{
                        memcpy(salt,train.context,salt_length);
                    } 
                    //测试
                    printf("%s\n",salt);//
                    skip_print = 1;
                }
                if(!skip_print){
                    printf("context=%s\n",train.context);

                }
            }
        }
    }
    return 0;

}
